import { defineProps, ref } from 'vue';
/* 选择文件组件，显示插槽内容 */
<template>
	<label class="choose-file">
		<input
			ref="chooseFile"
			type="file"
			:multiple="props.multiple"
			@change="changeFile"
		>
		<div @click="onclickSlot(chooseFile)"><slot /></div>
	</label>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
interface Props {
  multiple: boolean
}
const props = withDefaults(defineProps<Props>(), {
  multiple: false,
})
const emit = defineEmits<{
  (e: 'change', files: File[]|null): void
}>()

const chooseFile = ref(null)

/**
 * 点击插槽
 */
const onclickSlot = (dom:HTMLElement|null) => {
  if (dom) {
    dom.dispatchEvent(new MouseEvent('click'))
  }
}

/**
 * 选择文件
 */
const changeFile = (e:{target: any}) => {
  emit('change', Array.from(e.target.files))
}
</script>

<style lang="scss" scoped>
.choose-file {
  display: inline-block;

  input {
    position: absolute;
    left: 0;
    width: 0;
  }
}
</style>
